﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsMstsc.Models;

namespace WindowsMstsc.Forms
{
    /// <summary>
    /// 连接配置
    /// </summary>
    public partial class FrmConnectConfig : Form
    {
        public FrmConnectConfig()
        {
            InitializeComponent();
        }
        public FrmConnectConfig(MstscConfig mstscConfig) :this()
        {
            txtIP.Text = mstscConfig.IP;
            txtDescribe.Text = mstscConfig.Describe;
            txtName.Text = mstscConfig.Name;
            txtPassword.Text = mstscConfig.Password;
            txtPort.Text = mstscConfig.Port.ToString();
            txtUserName.Text = mstscConfig.UserName;
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtIP.Text) || !IPAddress.TryParse(txtIP.Text, out var address))
            {
                MessageBox.Show("IP异常");
                return;
            }
            if (string.IsNullOrEmpty(txtUserName.Text) || string.IsNullOrEmpty(txtPassword.Text))
            {
                MessageBox.Show("用户名密码异常");
                return;
            }
            if (string.IsNullOrEmpty(txtPort.Text) || !int.TryParse(txtPort.Text,out var port))
            {
                MessageBox.Show("端口异常");
                return;
            }
            MstscConfig mstscConfig = new MstscConfig()
            {
                Describe = txtDescribe.Text,
                IP = txtIP.Text,
                Name = txtName.Text,
                Password = txtPassword.Text,
                Port = port,
                UserName = txtUserName.Text,
                IsFullScreen = chkIsFullScreen.Checked
            };
            string key = mstscConfig.IP+"_"+port+"_"+mstscConfig.UserName;
            if (GlobalVar.AllConfigs.ContainsKey(key))
            {
                GlobalVar.AllConfigs[key] = mstscConfig;
            }
            else
            {
                GlobalVar.AllConfigs.Add(key, mstscConfig);
            }

            string json = JsonSerializer.Serialize(GlobalVar.AllConfigs);
            File.WriteAllText(GlobalVar.DB_FILE, json);
            this.DialogResult = DialogResult.OK;
            this.Close();
        }
    }
}
